package cn.com.lyb;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

public class SFTPFileDownloader {

    private static void downloadFilesFromDirectory(String host, int port, String user, String password, String remoteDirectory, String localDirectory) throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);

        // 配置会话属性
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(password);
        session.connect();

        // 打开 SFTP 通道
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();

        // 列出远程目录中的所有文件
        Vector<ChannelSftp.LsEntry> fileList = sftpChannel.ls(remoteDirectory);

        // 创建本地目录（如果不存在）
        File localDir = new File(localDirectory);
        if (!localDir.exists() && !localDir.mkdirs()) {
            throw new IOException("无法创建本地目录: " + localDirectory);
        }

        // 下载每个文件
        for (ChannelSftp.LsEntry entry : fileList) {
            String fileName = entry.getFilename();
            // 忽略目录本身（"." 和 ".."）
            if (".".equals(fileName) || "..".equals(fileName)) {
                continue;
            }

            String remoteFilePath = remoteDirectory + "/" + fileName;
            String localFilePath = localDirectory + File.separator + fileName;

            // 下载文件
            try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
                sftpChannel.get(remoteFilePath, fos);
                System.out.println("下载完成: " + fileName);
            }
        }

        // 关闭 SFTP 通道和会话
        sftpChannel.disconnect();
        session.disconnect();
    }

    public static void main(String[] args) {
        try {
            String host = "172.32.1.7";
            int port = 22; // 默认的SSH端口
            String user = "sftpuser";
            String password = "1QAZ@ws_yx";
            String remoteDirectory = "/ftp_home/ylg";
            String localDirectory = "D:\\logs";

            downloadFilesFromDirectory(host, port, user, password, remoteDirectory, localDirectory);
            System.out.println("所有文件下载成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("文件下载失败：" + e.getMessage());
        }
    }
}
